
package com.ssl.rms.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ssl.rms.constants.SystemConstant;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;

/**
 * 返回json数据的modelview
 */
public class JsonView extends AbstractView {

    public static final String DEFAULT_CONTENT_TYPE = "application/json;charset=UTF-8";

    public final static String CHARSET = "UTF-8";

    private SerializerFeature[] features = new SerializerFeature[]{SerializerFeature.PrettyFormat};

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model,
                                           HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (!response.isCommitted()) {
            response.reset();
            Object result = model.get(SystemConstant.ERROR_OBJECT);
            response.setContentType(DEFAULT_CONTENT_TYPE);
            response.setCharacterEncoding(CHARSET);
            OutputStream out = response.getOutputStream();
            String text = JSON.toJSONString(result, features);
            byte[] bytes = text.getBytes(CHARSET);
            out.write(bytes);
            out.flush();
        }
    }
}
